package com.caiyi.financial.nirvana.sms.gateway;

import com.caiyi.financial.nirvana.sms.entity.SmsGateway;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetAddress;

/**
 * 长连接网关基类
 */
public class KeepConnectGateWay extends DefaultGateWay {

    //日志
    private static final Logger logger = LoggerFactory.getLogger(KeepConnectGateWay.class);

    //启动
    public Bootstrap bootstrap;

    //事件组
    private EventLoopGroup group;

    private Channel channel;

    /**
     */
    public KeepConnectGateWay() {
        super();
    }

    @Override
    public void start() throws InterruptedException {
        group = new NioEventLoopGroup();
        bootstrap = new Bootstrap();
        bootstrap.group(group).channel(NioSocketChannel.class);
        bootstrap.option(ChannelOption.TCP_NODELAY, true);
        bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
        bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000);
    }

    //连接到服务器端
    @Override
    public void doConnect() {
        if (channel != null) {
            channel.close();
        }
        try {
            bootstrap.remoteAddress(InetAddress.getByName(info.getServerAddr()), info.getServerPort());
            channel = bootstrap.connect().sync().channel();
            logger.info("Started Tcp Client: " + info.getServerAddr() + ":" + info.getServerPort());
        } catch (Exception ex) {
            logger.error("doConnect error ", ex);
        }
    }

    @Override
    public void loginSuccess() {
        super.loginSuccess();
    }

    @Override
    public void terminated() {
        super.terminated();
        close();
    }

    @Override
    public void close() {
        logger.info(info.getName() + " close!");
        try {
            channel.close();
            group.shutdownGracefully();
            bootstrap = null;
        } catch (Exception e) {
        }
    }

    @Override
    public String toString() {
        return super.toString();
    }

    @Override
    public void init(SmsGateway info) {
        super.init(info);
    }
}